<?php

namespace App\Console\Commands\Shop;

use App\Kuafu\Guanyuan\Service\GuanyuanService;
use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use App\Kuafu\Mybank\Model\MybankShopBindModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopBusinessModel;
use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Exceptions\WaiMaiException;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Library\KfHttp\TigerCurl;
use App\Remote\Mybank\MybankCreateBatchRemote;
use Carbon\Carbon;
use ElemeOpenApi\Exception\PermissionDeniedException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ElmIncomeDaily extends Command
{
    protected $signature = 'waimaiIncome:eleme';

    protected $description = '外卖营收数据: 饿了么';

    // 手动修复数据标识
    protected $isManualFixData = false;

    /**
     * @throws WaiMaiException
     */
    public function handle()
    {
        if (isTest()) {
            return;
        }
        // 手动修复数据
        $beginDate             = date('Y-m-d H:i:s', strtotime('-7 day'));
        $headOfficeThirdShopId = 96099157;

        try {
            $result = BaseWaiMai::getIns(CodeEnum::SOURCE_TYPE_ELM, 0, $headOfficeThirdShopId)
                                ->queryBalanceLog($beginDate);

            $list = $result->pageList;
            $list = json_decode(json_encode($list), true);

            $targetList   = [];
            $countDcMarkC = 0;
            $transOut     = 0;
            $transTime    = 0;
            foreach ($list as $value) {
                if ($value['orderMes'] == '余额转出' && $value['transDcMark'] == 'C') {
                    if ($countDcMarkC == 0) {
                        $transOut  = $value['transAmount'];
                        $transTime = $value['transTime'];

                        // 非当天余额打款
                        if (!$this->isManualFixData) {
                            if (date('Y-m-d', ($value['transTime'] / 1000)) != date('Y-m-d')) {
                                break;
                            }
                        }
                    }
                    $countDcMarkC++;
                }

                if ($countDcMarkC > 1) {
                    break;
                }

                // 手动过滤某条数据
//                if ($value['transAmount'] == 22043.56) {
//                    $transOut = bcsub($transOut, $value['transAmount'], 2);
//                    continue;
//                }

                $targetList[] = $value;
            }

            // 数据没拿全 手动处理
            if ($countDcMarkC == 0) {
                Log::channel('mybank')->notice('饿了么暂无分账数据', [
                    'fsNotifyUids' => [
                        '3fgc8798'
                    ],
                    'msg'          => '饿了么当日无提现记录, 请手动提现或等待明日'
                ]);
                return false;
            }
            $totalDeposit  = '0';
            $thirdShopList = [];

            foreach ($targetList as $value) {
                $thirdId = self::getShopThirdId($value['orderMes']);
                if (empty($thirdId)) {
                    Log::channel('mybank')->info('饿了么分账数据-查询跳过', [
                        'mes' => $value['orderMes']
                    ]);
                    continue;
                }

                if ($value['orderMes'] == '余额转出') {
                    continue;
                }

                if (empty($thirdShopList[$thirdId])) {
                    $thirdShopList[$thirdId] = [
                        'transAmount' => 0,
                        'transTime'   => $transTime,
                        'transDcMark' => 'C',
                        'balance'     => 0,
                        'transStatus' => 1,
                        'orderMes'    => '余额转出',
                        'thirdId'     => $thirdId
                    ];
                }

                if ($value['transDcMark'] == 'C') {
                    $totalDeposit                           = bcsub($totalDeposit, $value['transAmount'], 2);
                    $thirdShopList[$thirdId]['transAmount'] = bcsub($thirdShopList[$thirdId]['transAmount'],
                        $value['transAmount'], 2);
                } else {
                    if ($value['transDcMark'] == 'D') {
                        $totalDeposit                           = bcadd($totalDeposit, $value['transAmount'], 2);
                        $thirdShopList[$thirdId]['transAmount'] = bcadd($thirdShopList[$thirdId]['transAmount'],
                            $value['transAmount'], 2);
                    } else {
                        Log::channel('mybank')->error('饿了么分账数据-出现了不存在的类型', [
                            'mes' => $value['orderMes']
                        ]);
                        continue;
                    }
                }
            }

            // 获取门店分到的总金额
            $thridTransAmountTotal = '0';
            foreach ($thirdShopList as $value) {
                $thridTransAmountTotal = bcadd($thridTransAmountTotal, $value['transAmount'], 2);
            }

            // 校验门店金额, 转账金额, 分账总账单金额
            if ($thridTransAmountTotal == $totalDeposit && $transOut == $totalDeposit) {
                Log::channel('mybank')->info('饿了么余额校准正确');
            } else {
                $this->info('$thridTransAmountTotal: ' . $thridTransAmountTotal);
                $this->info('$totalDeposit: ' . $totalDeposit);
                $this->info('$thridTransAmountTotal-$totalDeposit: ' . ($thridTransAmountTotal - $totalDeposit));
                $this->info('$transOut: ' . $transOut);
                $this->info('$totalDeposit: ' . $totalDeposit);
                $this->info('$transOut-$totalDeposit: ' . bcsub($transOut, $totalDeposit, 2));
                Log::channel('mybank')->error('饿了么余额校准不正确', [
                    'fsNotifyUids' => [
                        '3fgc8798'
                    ]
                ]);
                return false;
            }

            // 门店分账账单
            foreach ($targetList as $value) {
                self::dealInDb($value);
            }

            // 门店收入账单
            foreach ($thirdShopList as $value) {
                self::dealInDb($value);
            }

            return true;

        } catch (PermissionDeniedException $permissionDeniedException) {
            Log::channel('mybank')->error('waimaiIncome:eleme-ELEME_error', [
                'exception'    => $permissionDeniedException,
                'fsNotifyUids' => [
                    '3fgc8798'
                ]
            ]);
        } catch (\Exception $exception) {
            Log::channel('mybank')->error('waimaiIncome:eleme-error_ALL_EXCCEPTION', [
                'exception'    => $exception,
                'fsNotifyUids' => [
                    '3fgc8798'
                ]
            ]);
        }

    }

    private function dealInDb($value)
    {
        $transDate = $value['transTime'] / 1000;

        $thirdId = self::getShopThirdId($value['orderMes']) ?: $value['thirdId'] ?? '';
        if (empty($thirdId)) {
            Log::channel('mybank')->info('饿了么分账数据-查询跳过', [
                'mes' => $value['orderMes']
            ]);
            return;
        }

        // 通过三方的 shopId 获取 rms 的 shopId
        $wmShopInfo   = WaiMaiShopMappingModel::query()
                                              ->where('sourceType', WaiMaiDBEnum::SOURCE_TYPE_ELM)
                                              ->where('thirdShopId', $thirdId)
                                              ->first();
        $firstTransId = str_pad(bcmul($wmShopInfo->shopId, 100), 7, 0);
        $sendTransId  = MybankBillRecordModel::SOURCE_ELE . date('YmdHis0', $transDate);
        $thirdTransId = str_pad(bcmul(abs($value['transAmount']), 100), 10, 0);
        $transId      = $firstTransId . $sendTransId . $thirdTransId;

        list($transType, $displayTransType) = self::changeTransType($value);
        $billDate = self::getBillDate($value['orderMes']);

        MybankBillRecordModel::query()->updateOrCreate([
            'shopId'  => $wmShopInfo->shopId,
            'source'  => MybankBillRecordModel::SOURCE_ELE,
            'transId' => $transId
        ], [
            'transDate'            => $transDate,
            'transType'            => $transType,
            'displayTransType'     => $displayTransType,
            'transStatus'          => $value['transStatus'],
            'transDesc'            => $value['orderMes'],
            'billDate'             => $billDate,
            'transAmount'          => bcmul($value['transAmount'], 100),
            'afterRemainingAmount' => bcmul($value['balance'], 100),
            'remark'               => $value['orderMes'],
        ]);
    }

    /**
     * @throws WaiMaiException
     */
    public function handle3()
    {
        $beginDate             = date('Y-m-d H:i:s', strtotime('-4 day'));
        $headOfficeThirdShopId = 96099157;

        try {
            $result = BaseWaiMai::getIns(CodeEnum::SOURCE_TYPE_ELM, 0, $headOfficeThirdShopId)
                                ->queryBalanceLog($beginDate);

            $list = $result->pageList;

            dd($list);

            foreach ($list as $value) {
                $transDate = $value->transTime / 1000;

                $thirdId = self::getShopThirdId($value->orderMes);

                if (empty($thirdId)) {
                    Log::channel('mybank')->info('饿了么分账数据-查询跳过', [
                        'mes' => $value->orderMes
                    ]);
                    continue;
                }

                // 通过三方的 shopId 获取 rms 的 shopId
                $wmShopInfo = WaiMaiShopMappingModel::query()
                                                    ->where('sourceType', WaiMaiDBEnum::SOURCE_TYPE_ELM)
                                                    ->where('thirdShopId', $thirdId)
                                                    ->first();


                $firstTransId = str_pad(bcmul($wmShopInfo->shopId, 100), 7, 0);
                $sendTransId  = MybankBillRecordModel::SOURCE_ELE . date('YmdHis0', $transDate);
                $thirdTransId = str_pad(bcmul($value->transAmount, 100), 10, 0);
                $transId      = $firstTransId . $sendTransId . $thirdTransId;

                list($transType, $displayTransType) = self::changeTransType($value);
                $billDate = self::getBillDate($value->orderMes);

                MybankBillRecordModel::query()->updateOrCreate([
                    'shopId'  => $wmShopInfo->shopId,
                    'source'  => MybankBillRecordModel::SOURCE_ELE,
                    'transId' => $transId
                ], [
                    'transDate'            => $transDate,
                    'transType'            => $transType,
                    'displayTransType'     => $displayTransType,
                    'transStatus'          => $value->transStatus,
                    'transDesc'            => $value->orderMes,
                    'billDate'             => $billDate,
                    'transAmount'          => bcmul($value->transAmount, 100),
                    'afterRemainingAmount' => bcmul($value->balance, 100),
                    'remark'               => $value->orderMes,
                ]);
            }


        } catch (PermissionDeniedException $permissionDeniedException) {
            Log::channel('mybank')->error('waimaiIncome:eleme-ELEME_error', [
                'msg'          => $permissionDeniedException->getMessage(),
                'fsNotifyUids' => [
                    '3fgc8798'
                ]
            ]);
        } catch (\Exception $exception) {
            Log::channel('mybank')->error('waimaiIncome:eleme-error_ALL_EXCCEPTION', [
                'msg'          => $exception->getMessage(),
                'fsNotifyUids' => [
                    '3fgc8798'
                ]
            ]);
        }

    }

    public function handle2()
    {
        $beginDate = date('Y-m-d H:i:s', strtotime('-1 day'));

        // 获取已经绑定的门店 ID
        $shopIds = MybankShopBindModel::query()->select(['shopId'])->get();
        WaiMaiShopMappingModel::query()->where('sourceType', WaiMaiDBEnum::SOURCE_TYPE_ELM)
                              ->whereIn('shopId', $shopIds)
                              ->get()
                              ->each(function ($item, $key) use ($beginDate) {
                                  try {
                                      $result = BaseWaiMai::getIns(CodeEnum::SOURCE_TYPE_ELM, $item->shopId)
                                                          ->queryBalanceLog($beginDate);
                                      $list   = $result->pageList;

                                      foreach ($list as $value) {
                                          $transDate    = $value->transTime / 1000;
                                          $firstTransId = str_pad(bcmul($item->shopId, 100), 7, 0);
                                          $sendTransId  = MybankBillRecordModel::SOURCE_ELE . date('YmdHis0',
                                                  $transDate);
                                          $thirdTransId = str_pad(bcmul($value->transAmount, 100), 10, 0);
                                          $transId      = $firstTransId . $sendTransId . $thirdTransId;

                                          list($transType, $displayTransType) = self::changeTransType($value);
                                          $billDate = self::getBillDate($value->orderMes);
                                          MybankBillRecordModel::query()->updateOrCreate([
                                              'shopId'  => $item->shopId,
                                              'source'  => MybankBillRecordModel::SOURCE_ELE,
                                              'transId' => $transId
                                          ], [
                                              'transDate'            => $transDate,
                                              'transType'            => $transType,
                                              'displayTransType'     => $displayTransType,
                                              'transStatus'          => $value->transStatus,
                                              'transDesc'            => $value->orderMes,
                                              'billDate'             => $billDate,
                                              'transAmount'          => bcmul($value->transAmount, 100),
                                              'afterRemainingAmount' => bcmul($value->balance, 100),
                                              'remark'               => $value->orderMes,
                                          ]);
                                      }
                                  } catch (PermissionDeniedException $permissionDeniedException) {
                                      Log::error('waimaiIncome:eleme-ELEME_error', [
                                          'msg'    => $permissionDeniedException->getMessage(),
                                          'shopId' => $item->shopId
                                      ]);
                                  } catch (\Exception $exception) {
                                      Log::error('waimaiIncome:eleme-error_ALL_EXCCEPTION', [
                                          'msg'    => $exception->getMessage(),
                                          'shopId' => $item->shopId
                                      ]);
                                  }
                              });
    }

    public static function changeTransType($value)
    {
        if ($value['transDcMark'] == 'C') {
            if ($value['orderMes'] == '余额转出') {
                return [
                    MybankBillRecordModel::WITHDRAW_TRANS_TYPE,
                    MybankBillRecordModel::MAPPING_TRANS_TYPE[MybankBillRecordModel::WITHDRAW_TRANS_TYPE]
                ];
            } else {
                return [
                    MybankBillRecordModel::PAY_TRANS_TYPE,
                    MybankBillRecordModel::MAPPING_TRANS_TYPE[MybankBillRecordModel::PAY_TRANS_TYPE]
                ];
            }
        }

        if ($value['transDcMark'] == 'D') {
            return [
                MybankBillRecordModel::INCOME_TRANS_TYPE,
                MybankBillRecordModel::MAPPING_TRANS_TYPE[MybankBillRecordModel::INCOME_TRANS_TYPE]
            ];
        }

    }

    public static function getBillDate(string $orderMes)
    {
        try {
            $msg = explode('|', $orderMes);
            if (count($msg) > 2) {
                $billDate = substr($msg[2], 0, 10);
                return strtotime($billDate);
            } else {
                return 0;
            }
        } catch (\Exception $exception) {
            return 0;
        }

    }

    public static function getShopThirdId(?string $orderMes)
    {
        $pattern = '/\（(\d+)\）/';
        if (preg_match($pattern, $orderMes, $matches)) {
            $result = $matches[1];
            return $result;
        } else {
            return 0;
        }
    }
}
